#include "EWAUITrackHeaderVideo.hpp"

namespace Eyer
{
    EWAUITrackHeaderVideo::EWAUITrackHeaderVideo(EyerSmartPtr<EWAUITimelineContext> _timelineCtx, EWAUILayoutParams width, EWAUILayoutParams height)
        : EWAUITrackHeader(_timelineCtx, width, height)
    {
        SetWidgetName("EWAUITrackHeader_Video");
        SetLayoutType(EWAUILayoutType::LinearLayoutVertical);
    }

    EWAUITrackHeaderVideo::~EWAUITrackHeaderVideo()
    {

    }

    int EWAUITrackHeaderVideo::OnTrackUpdate(EWAPrjTimeline * timeline)
    {
        RemoveAllWidget();
        EWAPrjTrackType trackType = EWAPrjTrackType::VIDEO;

        for(int i = timeline->GetTrackCount(trackType) - 1; i >= 0; i--){
            EyerSmartPtr<EWAPrjTrackUI> track = timeline->GetTrack(i, trackType);

            AddWidget(track->segBar);
            AddWidget(track->item);
        }
        return 0;
    }

    bool EWAUITrackHeaderVideo::OnMousePressEvent(const Vec2I & pos)
    {
        return true;
    }

    bool EWAUITrackHeaderVideo::OnMouseReleaseEvent    (const Vec2I & pos)
    {
        firstMove = true;
        return true;
    }

    bool EWAUITrackHeaderVideo::OnMouseMoveEvent      (const Vec2I & pos)
    {
        EWAPrjTrackType trackType = EWAPrjTrackType::VIDEO;
        for(int i = 0; i < timelineCtx->timeline.GetTrackCount(trackType); i++) {
            EyerSmartPtr<EWAPrjTrackUI> track = timelineCtx->timeline.GetTrack(i, trackType);
            EyerSmartPtr<EWAUITrackHeaderItem> item = track->item;
            EyerSmartPtr<EWAUIWidgetVerticalSegBar> segBar = track->segBar;

            if (segBar == nullptr) {
                continue;
            }

            if(segBar->IsDraging()){
                if(firstMove){
                    pressPos = customXY;
                    originHeight = item->GetMinHeight();
                    firstMove = false;
                }

                int dHeight = - customXY.y() + pressPos.y();

                int targetHeight = originHeight + dHeight;
                if(targetHeight <= 0){
                    targetHeight = 0;
                }
                item->SetMinHeight(targetHeight);
                break;
            }
        }
        return true;
    }
}